package udpchatdemo02;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 实现相互发送接收消息
 *      通过多线程，
 *      发送端两个线程：
 *          一个发送端线程，用来发送消息
 *          一个接收端线程，用来接收消息
 *
 * 接收端类
 */
public class TalkReceive implements Runnable{
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;

    public TalkReceive(int port, String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }

    public void run() {
        // 一直聊天，知道对方说bye的时候，结束聊天
        while(true){
            // 准备接收数据的空包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);

            // 阻塞式接收包裹
            try {
                socket.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 接收到信息是bye的时候，结束聊天，断开连接
            String receiveDate = new String(packet.getData(),0,packet.getLength());
            System.out.println(msgFrom + ":" + receiveDate);

            if (receiveDate.equals("bye")){
                break;
            }
        }
        // 关闭链接
        socket.close();
    }
}
